package com.bgi.cg.oss4j.common.factory;

import com.bgi.cg.oss4j.common.config.OssConfig;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description TODO
 * @Author Z.cg
 * @Date 2023/9/8
 * @Version 1.0
 **/
public class BeanFactory {
    /**
     * 线程池
     */
    private static Executor executor;
    private static OssConfig ossConfig;
    private static final BeanFactory beanFactory = new BeanFactory();

    private BeanFactory() {
    }

    public static Executor setExecutor(OssConfig config) {
        if (executor == null) {
            // 创建一个线程池对象
            ThreadPoolExecutor ex = new ThreadPoolExecutor(
                config.getCorePoolSize(),
                config.getMaxPoolSize(),
                config.getQueueCapacity(),
                TimeUnit.SECONDS,
                new ArrayBlockingQueue(config.getMaxPoolSize())
            );
            // 线程池对拒绝任务的处理策略,当线程池没有处理能力的时候，该策略会直接在 execute 方法的调用线程中运行被拒绝的任务；如果执行程序已关闭，则会丢弃该任务
            ex.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
            executor = ex;
        }
        return executor;
    }

    public static Executor getExecutor() {
        return executor;
    }

    public static OssConfig getOssConfig() {
        if (ossConfig == null) {
            ossConfig = new OssConfig();
        }
        return ossConfig;
    }
}
